package com.jie.educenter.controller;

import com.google.gson.Gson;
import com.jie.commonutils.JwtUtils;
import com.jie.educenter.entity.UcenterMember;
import com.jie.educenter.service.UcenterMemberService;
import com.jie.educenter.utils.ConstantWxUtils;
import com.jie.educenter.utils.HttpClientUtils;
import com.jie.servicebase.exception.GuLiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 用于处理微信登录的Controller类
 * @author XieZhiJie
 * @create 2020-10-16 16:42
 */
//@CrossOrigin  // 处理跨域问题
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    private final UcenterMemberService memberService;

    @Autowired
    public WxApiController(UcenterMemberService memberService) {
        this.memberService = memberService;
    }

    /**
     * 获取扫描人信息, 添加数据
     * ps: 尚硅谷牛逼, 感谢尚硅谷
     * @param code   类似于手机验证码, 随机唯一值
     * @param state  原样传递的值
     * @return       重定向到前端页面
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        try {

            // 1.获取code值, 临时票据, 类似于验证码
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl =
                    "https://api.weixin.qq.com/sns/oauth2/access_token" +
                            "?appid=%s" +
                            "&secret=%s" +
                            "&code=%s" +
                            "&grant_type=authorization_code";
            // 拼接三个参数: id, 密钥, code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );

            // 2.使用code请求微信固定的地址, 得到两个值 access_token openid
            // 使用httpclient发送请求, 得到返回结果(模拟浏览器发送请求)
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            // 3.从accessTokenInfo中获取access_token和openid(转为map)
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            // 4.把扫码人信息添加到数据库中
            // 判断数据库表中是否存在相同的微信信息(根据openid查询)
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null) {  // 表中无数据, 添加

                // 得到access_token和openid, 再去请求微信提供固定的地址, 获取扫描人信息
                // 访问微信的资源服务器, 获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                // 传入参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );

                // 发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                // 获取返回的userInfo字符串扫描人的信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                // 获取昵称
                String nickname = (String) userInfoMap.get("nickname");
                // 获取头像信息
                String headImgUrl = (String) userInfoMap.get("headimgurl");

                // 保存(注册)用户信息
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headImgUrl);
                memberService.save(member);
            }

            // 5.生成token
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            // 6.返回到首页面(传递token)
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuLiException(20001, "登录异常!");
        }
    }

    /**
     * 生成微信扫描二维码
     * @return  重定向到请求微信地址
     */
    @GetMapping("/login")
    public String getWxCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
            throw new GuLiException(20001, "编码异常!");
        }

        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "jie"
        );

        // 重定向到请求微信地址
        return "redirect:" + url;
    }

}
